package com.flex.reflection.convert;

import com.flex.reflection.MetaClass;
import com.flex.reflection.util.DateUtils;
import org.apache.commons.lang.math.NumberUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

/**
 * @author ganlt
 * @since 2019/09/23 13:57
 */
public class FieldDateConvert implements FieldConvert {
    private MetaClass.Config config;

    public FieldDateConvert(MetaClass.Config config) {
        this.config = config;
    }
    @Override
    public Object convert(Object type) {
        if (type == null) {
            return null;
        }
        Class<?> aClass = type.getClass();

        if (aClass.isAssignableFrom(BigInteger.class)) {
            BigInteger bigInteger = (BigInteger) type;
            return new Date(bigInteger.intValue());
        }

        if (aClass.isAssignableFrom(BigDecimal.class)) {
            BigDecimal bigDecimal = (BigDecimal) type;
            return new Date(bigDecimal.intValue());
        }

        if (aClass.isAssignableFrom(String.class)) {
            String str = (String) type;
            if (NumberUtils.isNumber(str)) {
                return new Date(Integer.valueOf(str));
            } else {
                return DateUtils.convert(str,config.getDateFormat());
            }
        }

        try {
            return new Date(Integer.parseInt(type.toString()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



}
